# -*- coding: utf-8 -*-

from django.http import HttpResponse
from django.core import serializers

from worlddb.utils import render_response
from worlddb.models import *

def _returntype(list, type='json'):
    try:
        l = serializers.serialize(type,  list)
        return HttpResponse(l, mimetype="application/" + type)
    except Exception, e:
        return HttpResponse(str(e), mimetype="text/plain")

def _getdata(request, list):
    if 'returntype' in request.GET and request.GET['returntype'] == 'xml':
        return _returntype(list, type='xml')
    else:
        return _returntype(list)

def update_worlddb_form(request, form):
    if(request.POST['region'] != ''):
        form['region'].field.queryset = Region.objects.filter(country=long(request.POST['country']))
        if(request.POST['city'] != ''):
            form['city'].field.queryset = City.objects.filter(region=long(request.POST['region']))

def regions(request, country):
    list = get_regions_of_country(long(country))
    return _getdata(request, list)
    
def cities(request, region):
    list = get_cities_of_region(long(region))
    return _getdata(request, list)
